import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';

import '../../config/Constant.dart';
import '../../model/UserEntity.dart';
import '../Tool/MyTools.dart';

part 'user_state.dart';

/// UserBloc操作集中管理
class UserBlocTool {
  //缓存当前用户信息
  static UserEntity? userEntity = null;

  //缓存当前用户凭证
  static String? userAuth;

  //保存用户凭证
  static Future<bool>? saveAuth(String auth) {
    userAuth = auth;
    return SpUtil.putString(Constant.Authorization, auth);
  }

  //删除用户凭证
  static Future<bool>? removeAuth() {
    userAuth = null;
    return SpUtil.remove(Constant.Authorization);
  }

  //获取用户凭证
  static Future<String?> getUserAuth() async {
    if (!MyTools.stringIsEmpty(userAuth)) {
      return userAuth;
    }

    String? auth = await SpUtil.getString(Constant.Authorization);
    if (!MyTools.stringIsEmpty(auth)) {
      userAuth = auth;
    }

    return auth;
  }

  static exit() async {
    await UserBlocTool.removeAuth();
    UserBlocTool.userEntity = null;
    SpUtil.clear();
  }

//更新 userEntity
  static update(UserEntity user) {
    userEntity = user;
    SpUtil.putString(Constant.User, jsonEncode(userEntity?.toJson()));
  }

  ///返回当前用户对象
  static UserEntity? getUser() {
    if (userEntity != null) {
      return userEntity;
    }

    try {
      String? json = SpUtil.getString(Constant.User);
      if (!MyTools.stringIsEmpty(json)) {
        UserEntity user = UserEntity.fromJson(jsonDecode(json!));
        userEntity = user;
        return user;
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  ///是否登录
  static bool isLogin() {
    UserEntity? entity = getUser();
    if (entity != null) {
      return !MyTools.stringIsEmpty(entity.id);
    }
    return false;
  }

  ///返回当前用户对象uid
  static String uid() {
    UserEntity? userEntity = getUser();

    if (userEntity != null) {
      if (!MyTools.stringIsEmpty(userEntity.id)) {
        return userEntity.id!;
      }
    }

    return "";
  }
}
